import { login, loginCode, sendNoteCode, supplierLogin } from '@/api/user'
import { getUserInfo } from '@/service'
import {
  getToken,
  setToken,
  removeToken,
  setLs,
  getLs,
  clearLs
} from '@/utils/auth'
import {target} from "@/utils/config";
import router, { resetRouter } from '@/router'
import Layout from "@/layout";
import {usersMenu} from '../config/usersMenu'

// 自定义用户信息
const state = {
  token: getToken(),
  name: getLs('name'),
  avatar: getLs('avatar'),
  roles: getLs(`roles-${target}`),
  hasRegister: false, // 是否已经注册路由
  userId: getLs('userId'),
  users: getLs('users')
}

let roles = []
const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token
    setToken(token)
  },
  DEL_TOKEN: state => {
    state.token = ''
    removeToken()
  },
  SET_NAME: (state, name) => {
    state.name = name
    setLs('name', name)
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
    setLs('avatar', avatar)
  },
  SET_ROLES: (state, roles) => {
    console.log('roles ----', roles)
    state.roles = roles
    setLs(`roles-${target}`, roles)
  },
  SET_USERID: (state, userId) => {
    state.userId = userId
    setLs('userId', userId)
  },
  SET_HASREGISTER: (state, flag) => {
    state.hasRegister = flag
  },
  SET_USERS: (state, user) => {
    state.users = user
    setLs('users', user)
  }
}

const actions = {
  // user login
  sendCode({ commit, dispatch }, params) {
    const { phone } = params
    return new Promise((resolve, reject) => {
      // 调用api/user.js
      const params = {
        phone
      }
      sendNoteCode(params)
        .then(response => {
          resolve()
        })
        .catch(error => {
          reject(error)
        })
    })
  },
  // user login
  login({ commit, dispatch }, userInfo) {
    const { username, password, target, code, key, isPhoneLogin, loginType, phone, smsKey, snsCode } = userInfo
    return new Promise((resolve, reject) => {
      // 调用api/user.js
      if(isPhoneLogin) {
        const params = {
          phone,
          code,
        }

        if(target === 'platform') {
          params.userType = 4
        } else if(target === 'users') {
          params.userType = 6
        }
        loginCode(params)
          .then(response => {
            const { data } = response
            // debuggern
            console.log('loginData ---', response)

            if (!data) {
              reject('验证失败，请重新登录.')
            }

            window.localStorage.setItem(`token-${target}`, data.access_token)
            commit('SET_TOKEN', data.access_token) // 后端接口返回的token
            commit(
              'SET_AVATAR',
              'https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif'
            )
            // 获取登录权限
            roles = []
            getUserInfo({}).then((childRes) => {
              // setToken(data.access_token)
              let routerVos = childRes.data.roles
              const supplierRouter = ['maskManagerIndex', 'companyInfo']
              let users = childRes.data.user
              console.log('users ---', users)
              users.target = target
              window.localStorage.setItem(`users-${users.target}`, JSON.stringify(users))

              // if(target === 'platform') {
              //   flatArrayList(newRouterVos)
              // } else if(target === 'users') {
              //   roles = usersMenu.slice()
              // }

              flatArrayList(routerVos)
              console.log('roles ---', roles)
              commit('SET_ROLES', routerVos)
              resolve(true)
            })
          })
          .catch(error => {
            reject(error)
          })
      } else {
        const params = {
          username,
          password,
        }

        login(params)
          .then(response => {
            const { data } = response
            // debuggern
            console.log('loginData ---', response)

            if (!data) {
              reject('验证失败，请重新登录.')
            }

            window.localStorage.setItem(`token-${target}`, data.token)
            commit('SET_TOKEN', data.access_token) // 后端接口返回的token
            commit(
              'SET_AVATAR',
              'https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif'
            )
            // 获取登录权限
            roles = []
            getUserInfo({}).then((childRes) => {
              // setToken(data.access_token)
              let routerVos = childRes.data.roles
              const supplierRouter = ['maskManagerIndex', 'companyInfo']
              let users = childRes.data.user

              let newRouterVos = []
              // routerVos.forEach((item) => {
              //   let routerChild = []
              //   item.children && item.children.forEach((child) => {
              //     if(supplierRouter.indexOf(child.name) === -1) {
              //       routerChild.push(child)
              //     }
              //   })
              //   item.children = routerChild
              //
              //   if(supplierRouter.indexOf(item.name) === -1) {
              //     newRouterVos.push(item)
              //   }
              // })

              flatArrayList(routerVos)

              commit('SET_ROLES', roles)
              resolve(true)
            })
          })
          .catch(error => {
            reject(error)
          })
      }

    })
  },
  // get user info
  getRoles({ commit, state }) {
    return new Promise((resolve, reject) => {
      resolve(getLs('rules'))
    })
  },

  // get user info
  // getInfo({ commit, state }) {
  //   return new Promise((resolve, reject) => {
  //     getUserPermission(state.token)
  //       .then(response => {
  //         //  = response.data
  //         const { data } = response
  //         console.log({ data })

  //         if (!data) {
  //           reject('验证失败，请重新登录.')
  //         }
  //         // roles["xxx:page"],name用户名称/或者存用户对象，avatar头像，可以去掉
  //         const { roles, users } = data

  //         if (!roles || roles.length <= 0) {
  //           reject('getUserPermission: 角色必须是非空数组!')
  //         }
  //         // console.log("roles:"+roles);
  //         // console.log("users:"+JSON.stringify(users));

  //         // 用户信息，用户的权限，固定头像
  //         commit('SET_USERID', users.id)
  //         commit('SET_ROLES', roles)
  //         commit('SET_NAME', users.userName)
  //         commit(
  //           'SET_AVATAR',
  //           'https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif'
  //         )
  //         resolve(data)
  //       })
  //       .catch(error => {
  //         reject(error)
  //       })
  //   })
  // },

  // user logout
  logout({ commit, state, dispatch }) {
    return new Promise((resolve, reject) => {
      console.log('==========================>logout')
      commit('SET_TOKEN', '')
      commit('DEL_TOKEN')
      commit('SET_ROLES', [])
      commit('SET_USERID', 1)
      commit('SET_USERS', {})
      commit('SET_HASREGISTER', false)
      removeToken()
      // clearLs()
      dispatch('tagsView/delAllViews', null, { root: true })
      window.localStorage.removeItem(`token-${target}`)
      window.localStorage.removeItem(`users-${target}`)
      console.log('123')
      // if(target === 'platform') {
      //   router.replace('/cjht/jzkc/login')
      // } else {
      //   router.replace('/sass/jzkc/login')
      // }
      resolve()
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      console.log('==========================>resetToken')
      commit('SET_TOKEN', '')
      commit('SET_ROLES', [])
      commit('SET_USERID', 1)
      commit('SET_USERS', {})
      commit('SET_HASREGISTER', false)
      removeToken()
      clearLs()
      resolve()
    })
  },

  // remove token
  doRegister({ commit }, flag) {
    return new Promise(resolve => {
      commit('SET_HASREGISTER', flag)
      resolve()
    })
  },

  // 动态地修改权限
  async changeRoles({ commit, dispatch }, role) {
    const token = role + '-token'

    commit('SET_TOKEN', token)
    setToken(token)

    // 拉去user_info
    const { roles } = await dispatch('getInfo')

    resetRouter()

    // 根据角色生成可访问路由图
    const accessRoutes = await dispatch('permission/generateRoutes', roles, {
      root: true
    })
    // 动态添加可访问路由
    router.addRoutes(accessRoutes)

    // 重置已访问的视图和缓存的视图
    dispatch('tagsView/delAllViews', null, { root: true })
  }
}

function flatArrayList(list) {
  // eslint-disable-next-line no-undef
  if (Array.isArray(list)) {
    list.forEach((item) => {
      if (item.children) {
        roles.push(item.name)
        flatArrayList(item.children)
      } else {
        roles.push(item)
      }
    })
  }
}
export default {
  namespaced: true,
  state,
  mutations,
  actions
}
